//
//  AppDelegate.m
//  CheekiOS
//
//  Created by mac on 2017/5/8.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "AppDelegate.h"
#import "MZCNavigationController.h"
#import "MZCTabBarController.h"
#import "GifloginViewController.h"
#import "HQRCDataSource.h"//同步好友列表
//自定义融云注册
#import "HRMessage.h"
#import "HRTextMessage.h"
#import "HRGiftMessage.h"

#import "WXApi.h"
#import "TencentOAuth.h"
#import "QQApiInterfaceObject.h"
#import "WeiboSDK.h"


//注册信息补全
#import "RegisterInfoViewController.h"
#import "RegisterPhotoViewController.h"
//高德地图
#import <AMapFoundationKit/AMapFoundationKit.h>
//腾讯云
#import <ILiveSDK/ILiveSDK.h>
#import <ImSDK/ImSDK.h>

@interface AppDelegate ()<RCIMReceiveMessageDelegate,RCIMConnectionStatusDelegate,CLLocationManagerDelegate>
{
    int isFrist;
    // 发送请求参数
    NSString *longitude;
    NSString *latitude;
    NSString *address;

}
@property (nonatomic,strong ) CLLocationManager * locationManger;
@property (nonatomic,strong ) MZCTabBarController *tabbar;
@property (nonatomic, strong) UserpersionlInfoModel *infoModel;

@property (nonatomic, assign) NSInteger friendMessageCount;
@property (nonatomic, assign) NSInteger friendLikeCount;


@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//    [SVProgressHUD setMinimumDismissTimeInterval:1.0];
    

    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    

    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        UIUserNotificationSettings *settings = [UIUserNotificationSettings
                                                settingsForTypes:(UIUserNotificationTypeBadge |
                                                                  UIUserNotificationTypeSound |
                                                                  UIUserNotificationTypeAlert)
                                                categories:nil];
        [application registerUserNotificationSettings:settings];
    } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
        //categories 必须为nil
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeAlert |
        UIRemoteNotificationTypeSound;
        [application registerForRemoteNotificationTypes:myTypes];
#pragma clang diagnostic pop
    }
    
    
    [self MessageRequestCount];
    //定位开启
    
    [self didLocation];
    
    
    //注册腾讯云
    TIMManager *manager = [[ILiveSDK getInstance] getTIMManager];
    [manager setEnv:0];
    //默认debug等级
    [manager initLogSettings:NO logPath:[manager getLogPath]];
    [manager setLogLevel:(TIMLogLevel)TIM_LOG_NONE];
    
    [[ILiveSDK getInstance] initSdk:[ShowCloudAppId intValue] accountType:[ShowCloudAccountType intValue]];
    
    
    

    
    //自定义融云注册
    [[RCIM sharedRCIM] initWithAppKey:kRongYunAppKey];
    [[RCIM sharedRCIM] registerMessageType:[HRMessage class]];
    [[RCIM sharedRCIM] registerMessageType:[HRTextMessage class]];
    [[RCIM sharedRCIM] registerMessageType:[HRGiftMessage class]];
    [RCIM sharedRCIM].receiveMessageDelegate = self;
    [[UINavigationBar appearance] setTintColor:TheMainColor];
    [RCIM sharedRCIM].globalNavigationBarTintColor = TheMainColor;


    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(didReceiveMessageNotification:)
     name:RCKitDispatchMessageNotification
     object:nil];
    
    //查看是否有登录信息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initRongCloudSetting:) name:KNOTIFICATION_isLogin object:nil];
    [[RCIMClient sharedRCIMClient] recordLaunchOptionsEvent:launchOptions];
    
    /**
     * 获取融云推送服务扩展字段
     * nil 表示该启动事件不包含来自融云的推送服务
     */
    NSDictionary *pushServiceData = [[RCIMClient sharedRCIMClient] getPushExtraFromLaunchOptions:launchOptions];
    if (pushServiceData) {
        NSLog(@"该启动事件包含来自融云的推送服务");
        for (id key in [pushServiceData allKeys]) {
            NSLog(@"%@", pushServiceData[key]);
        }
    } else {
        NSLog(@"该启动事件不包含来自融云的推送服务");
    }
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                NSLog(@"未知网络");
                break;
            case AFNetworkReachabilityStatusNotReachable:
            {// 没有网络(断网)
                NSLog(@"没有网络(断网)");
//                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"网络连接已断开" message:nil preferredStyle:UIAlertControllerStyleAlert];
//                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//                    
//                }];
//                [alertVC addAction:cancelAction];
//                [self.window.rootViewController presentViewController:alertVC animated:YES completion:nil];
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                NSLog(@"手机自带网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                NSLog(@"WIFI");
                break;
        }

    }];
    
    [mgr startMonitoring];
    
    if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized)) {
        
        //定位功能可用
        
    } else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"定位没有打开" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertVC addAction:cancelAction];
        [self.window.rootViewController presentViewController:alertVC animated:YES completion:nil];
    }
//    //通讯录授权
//    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
//    //     2.如果不是已经授权,则直接返回
//    if (status != CNAuthorizationStatusAuthorized) {
//        //通讯录提醒
//        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"通讯录没有打开" message:nil preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//            
//        }];
//        [alertVC addAction:cancelAction];
//        
//        [self.window.rootViewController presentViewController:alertVC animated:YES completion:nil];
//    }
    [RCIMClient sharedRCIMClient].logLevel = RC_Log_Level_Info;
    
    
    //--设置app的设置(个人隐私设置)
    [self setPersionalUSD];
    //配置beeCloud
//    [BeeCloud initWithAppID:@"a0dbd452-2c72-46be-a6bb-bee64e7e4789" andAppSecret:@"0f10fc06-3c8b-4cfd-a16f-f954ddd7ae08" sandbox:NO];
    
//    [BeeCloud initWeChatPay:@"wxed66bd853a316bc6"];
   
    //配置高德
    [AMapServices sharedServices].apiKey = @"d507b2987b923076ed321c07f0dc9e88";

    //配置三方分享 UM配置
    [self setUMShare];
    
    if([[defaults objectForKey:@"isFirstComeIn"] intValue] == 0){

        GifloginViewController *logVC = [[GifloginViewController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:logVC];
        self.window.rootViewController = nav;
        
    }else{
        
        NSString* identifierNumber = [[UIDevice currentDevice].identifierForVendor UUIDString] ;
        NSLog(@"手机序列号: %@",identifierNumber);
        NSString *str =  [self intervalSinceNow:[defaults objectForKey:@"loginTime"]];
        NSLog(@"%@",str);
        
        
        if ([str isEqualToString:@"剩余-90天"]) {
            GifloginViewController *logVC = [[GifloginViewController alloc] init];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:logVC];
            self.window.rootViewController = nav;
        }else{
            [self setUpRongYun];

            
                if ([[defaults objectForKey:@"infoStatus"] isEqualToString:@"ok"]) {
                    
                    MZCTabBarController *TabVC =   [[MZCTabBarController alloc] init];
                    self.window.rootViewController  = TabVC;
                }
                else if ([[defaults objectForKey:@"infoStatus"] isEqualToString:@"baseinfo"]){
                    
                    
                    RegisterInfoViewController *infoVC = [[RegisterInfoViewController alloc] init];
                    infoVC.perfectType =@"1";
                    [defaults removeObjectForKey:@"perfectloginName"];
                    [defaults removeObjectForKey:@"perfectloginBirthday"];
                    [defaults synchronize];
                    self.window.rootViewController  = infoVC;
                    
                    [self.window makeKeyAndVisible];
                }else if ([[defaults objectForKey:@"infoStatus"] isEqualToString:@"photo"]){
                    RegisterPhotoViewController *photoVC = [[RegisterPhotoViewController alloc] init];
                    photoVC.sexNum = [HQHttpManager getUserSex];
                    [defaults removeObjectForKey:@"perfectloginName"];
                    [defaults removeObjectForKey:@"perfectloginBirthday"];
                    [defaults synchronize];
                    photoVC.perfectType =@"1";
                    self.window.rootViewController  = photoVC;
                }
                
        }
        
    }

    
 

    
    [self.window makeKeyAndVisible];

    // 显示小红点
//    [self showUnreadMessageHotView];
    return YES;
}
//判断登录时间是否超时
- (NSString *)intervalSinceNow: (NSString *) theDate{
    NSArray *timeArray=[theDate componentsSeparatedByString:@"."];
    
    theDate=[timeArray objectAtIndex:0];
    
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
    
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *d=[date dateFromString:theDate];
    
    NSTimeInterval late=[d timeIntervalSince1970]*1;
    NSDate* dat = [NSDate date];
    NSTimeInterval now=[dat timeIntervalSince1970]*1;
    NSString *timeString=@"";
    
    NSTimeInterval cha=late-now;
    
    if (cha/3600<1) {
        timeString = [NSString stringWithFormat:@"%f", cha/60];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"剩余%@分", timeString];
        
    }
    if (cha/3600>1&&cha/86400<1) {
        timeString = [NSString stringWithFormat:@"%f", cha/3600];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"剩余%@小时", timeString];
    }
    if (cha/86400>1)
    {
        timeString = [NSString stringWithFormat:@"%f", cha/86400];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"剩余%@天", timeString];
        
    }
    
    return timeString;
}
//注册后登录
- (void)initRongCloudSetting :(NSNotification *)noti{
    
    
    [self setUpRongYun];

    
        if ([[defaults objectForKey:@"infoStatus"] isEqualToString:@"ok"]) {
            
            
            
            MZCTabBarController *TabVC =   [[MZCTabBarController alloc] init];
            
            self.window.rootViewController  = TabVC;
            
            
        }
        else if ([[defaults objectForKey:@"infoStatus"] isEqualToString:@"baseinfo"]){
            
            
            RegisterInfoViewController *infoVC = [[RegisterInfoViewController alloc] init];
            self.window.rootViewController  = infoVC;
            
            [self.window makeKeyAndVisible];
            
        }else if ([[defaults objectForKey:@"infoStatus"] isEqualToString:@"photo"]){
            
            
            RegisterPhotoViewController *photoVC = [[RegisterPhotoViewController alloc] init];
            photoVC.sexNum = [HQHttpManager getUserSex];
            self.window.rootViewController  = photoVC;
            
        }
    
        

}
- (void)didReceiveMessageNotification:(NSNotification *)notification {
    RCMessage *message = notification.object;
    if (message.messageDirection == MessageDirection_RECEIVE) {
        [UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber + 1;
    }
    
    if([[defaults objectForKey:@"allowToMessageShake"]isEqualToString:@"allowToMessageShakeYES"]){
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }else{
        AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate);
    }
    
}
//消息标志通知
- (void)setBadgeValueWithCount:(NSInteger)count {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"KNOTIFICATION_ReceiveMessage" object:nil];
}
#pragma mark RCIMReceiveMessageDelegate
- (void)onRCIMReceiveMessage:(RCMessage *)message left:(int)left {
    NSInteger count = [[RCIMClient sharedRCIMClient] getTotalUnreadCount];
    
    [self setBadgeValueWithCount:count];
    
    NSLog(@"ReceiveMessage=%@",message.content);
    if ([message.content isMemberOfClass:[HRTextMessage class]]) {
        HRTextMessage *TxtMsg = (HRTextMessage *)message.content;
        NSLog(@"extra = %@",TxtMsg.extra);
        if ([TxtMsg.extra isEqualToString:@"phone"]) {
            NSLog(@"TxtMsg=%@",TxtMsg);
            [[RCIM sharedRCIM] sendMessage:ConversationType_PRIVATE targetId:message.targetId content:[HRTextMessage messageWithContent:[HQHttpManager userAccount] extra:nil uid:[HQHttpManager getUserId] trystId:nil type:nil] pushContent:@"phone" pushData:nil success:^(long messageId) {
                
            } error:^(RCErrorCode nErrorCode, long messageId) {
                
            }];
        }
    }
}
//注册融云
- (void)setUpRongYun {
    
    //登录腾讯云
    
    NSString *CheekSig = [defaults objectForKey:@"cheekVodepSig"] ;
    
    [[ILiveLoginManager getInstance] iLiveLogin:[HQHttpManager getUserId] sig:CheekSig succ:^{
        NSLog(@"腾讯云=============================登录成功");
        [[RCIM sharedRCIM] setGlobalMessageAvatarStyle:RC_USER_AVATAR_CYCLE];
        [[RCIM sharedRCIM] setGlobalConversationAvatarStyle:RC_USER_AVATAR_CYCLE];
        [[RCIM sharedRCIM] setConnectionStatusDelegate:self];
        [[RCIM sharedRCIM] setEnableMessageAttachUserInfo:YES];
        if (iPhone6p) {
            [RCIM sharedRCIM].globalConversationPortraitSize = CGSizeMake(56, 56);
        } else {
            [RCIM sharedRCIM].globalConversationPortraitSize = CGSizeMake(46, 46);
        }
        //设置用户信息源和群组信息源
        [RCIM sharedRCIM].userInfoDataSource = RCDDataSource;
        [RCIM sharedRCIM].groupInfoDataSource = RCDDataSource;
        //设置群组内用户信息源。如果不使用群名片功能，可以不设置
        [RCIM sharedRCIM].groupUserInfoDataSource = RCDDataSource;
        //设置接收消息代理
        [RCIM sharedRCIM].receiveMessageDelegate=self;
        NSString *token = [HQHttpManager getUserToken];
        NSString *userId = [HQHttpManager getUserId];
        NSString *password = [HQHttpManager userPassword];
        NSString *userNickName = [HQHttpManager userNickName];
        NSString *userPortraitUri = [HQHttpManager userPhoto];
        
        if (token.length && userId.length) {
            RCUserInfo *_currentUserInfo =
            [[RCUserInfo alloc] initWithUserId:userId
                                          name:userNickName
                                      portrait:HttpImgUrl(userPortraitUri)];
            [RCIM sharedRCIM].currentUserInfo = _currentUserInfo;
            // 整个程序只调用一次
            [[RCIM sharedRCIM] connectWithToken:token
                                        success:^(NSString *userId) {
                                            NSLog(@"%@",userId);
                                            //消息列表刷新通知
                                            [[NSUserDefaults standardUserDefaults] setValue:userId forKey:@"RCIMUserId"];
                                            NSString *Str = @"rcimconnerct";
                                            [[NSNotificationCenter defaultCenter] postNotificationName:Str object:nil
                                             ];

                                        }error:^(RCConnectErrorCode status) {
                                            
                                        }tokenIncorrect:^{
                                            NSLog(@"已过期");
                                        }];
            
        }

        
        
    } failed:^(NSString *moudle, int errId, NSString *errMsg) {
        NSLog(@"腾讯云=============================登录失败");
    }];
    
    
    
    
 }

#pragma mark RCIMConnectionStatusDelegate
/**
 *  网络状态变化。
 *
 *  @param status 网络状态。
 */
- (void)onRCIMConnectionStatusChanged:(RCConnectionStatus)status {
    if (status == ConnectionStatus_KICKED_OFFLINE_BY_OTHER_CLIENT) {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"提示"
                              message:@"您"
                              @"的帐号在别的设备上登录，您被迫下线！"
                              delegate:nil
                              cancelButtonTitle:@"知道了"
                              otherButtonTitles:nil, nil];
        [alert show];


        [defaults removeObjectForKey:@"isFirstComeIn"];
        [defaults setObject:@"0" forKey:@"isFirstComeIn"];
        [defaults synchronize];
        [[RCIM sharedRCIM] logout];
        [[ILiveLoginManager getInstance] iLiveLogout:^{
            NSLog(@"腾讯云退出等路");
        } failed:^(NSString *module, int errId, NSString *errMsg) {
            
        }];
        GifloginViewController *loginVC = [[GifloginViewController alloc] init];
        UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
        self.window.rootViewController = nav;
        
    }else if (status == ConnectionStatus_TOKEN_INCORRECT) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
    }
}
#pragma mark ======================推送=======================
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    /**
     * 统计推送打开率3
     */
    [[RCIMClient sharedRCIMClient] recordLocalNotificationEvent:notification];
    
    //  //震动
    //  AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    //  AudioServicesPlaySystemSound(1007);
}
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
    // register to receive notifications
    [application registerForRemoteNotifications];
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token =
    [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"
                                                           withString:@""]
      stringByReplacingOccurrencesOfString:@">"
      withString:@""]
     stringByReplacingOccurrencesOfString:@" "
     withString:@""];
    
    [[RCIMClient sharedRCIMClient] setDeviceToken:token];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler {
    /**
     * 统计推送打开率
     */
    [[RCIMClient sharedRCIMClient] recordRemoteNotificationEvent:userInfo];
    
    /**
     * 获取融云推送服务扩展字段
     * nil 表示该启动事件不包含来自融云的推送服务
     */
    NSDictionary *pushServiceData = [[RCIMClient sharedRCIMClient] getPushExtraFromRemoteNotification:userInfo];
    if (pushServiceData) {
        NSLog(@"该远程推送包含来自融云的推送服务");
        for (id key in [pushServiceData allKeys]) {
            NSLog(@"key = %@, value = %@", key, pushServiceData[key]);
        }
    } else {
        NSLog(@"该远程推送不包含来自融云的推送服务");
    }
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
    int unreadMsgCount = [[RCIMClient sharedRCIMClient] getUnreadCount:@[@(ConversationType_PRIVATE),
                                                                         @(ConversationType_DISCUSSION),
                                                                         @(ConversationType_APPSERVICE),
                                                                         @(ConversationType_PUBLICSERVICE),
                                                                         @(ConversationType_GROUP)]];
    application.applicationIconBadgeNumber = unreadMsgCount;
}
#pragma mark***********************************友盟**********************************************
#pragma mark - setUMShare
//友盟分享 登录
-(void)setUMShare{
    
    /* 设置友盟appkey */
    [[UMSocialManager defaultManager] setUmSocialAppkey:@"591e677865b6d6704e000313"];
    
    
    /* 打开调试日志 */
    [[UMSocialManager defaultManager] openLog:YES];

    
    [self configUSharePlatforms];
    
}
- (void)configUSharePlatforms{

    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxed66bd853a316bc6" appSecret:@"92890cc596f2e1e73c4a1dc0658c9701" redirectURL:nil];
    /*
     * 移除相应平台的分享，如微信收藏
     */
    [[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
    
    /* 设置分享到QQ互联的appID
     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1106175044"/*设置QQ平台的appID*/  appSecret:@"4M5EqGyG0VEknCIB" redirectURL:@"http://mobile.umeng.com/social"];

    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Qzone appKey:@"1106175044"/*设置QQ平台的appID*/  appSecret:@"4M5EqGyG0VEknCIB" redirectURL:@"http://mobile.umeng.com/social"];

    /* 设置新浪的appKey和appSecret */
//    [WeiboSDK enableDebugMode:YES];//调试模式就打开

//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:@"3923337970"  appSecret:@"c0a98ed207395a7a4901b197e2035735" redirectURL:@"http://sns.whalecloud.com/sina2/callback"];

    
}
#pragma mark - 此方法用于处理从微信、支付宝钱包回到本应用时的回调
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {

    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return YES;
}
//iOS9之后官方推荐用此方法
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    
 
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
    }

    return YES;
}
#pragma mark - =====================定位 授权  开启=======================
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([self.locationManger respondsToSelector:@selector(requestAlwaysAuthorization)])
            {
                [self.locationManger requestWhenInUseAuthorization];
            }
            break;
        default:
            break;
    }
    
}

- (void)didLocation {
    if ([CLLocationManager locationServicesEnabled]) {
        //定位功能可用，开始定位
        self.locationManger = [[CLLocationManager alloc] init];
        self.locationManger.delegate = self;
        if ([[[UIDevice currentDevice] systemVersion] floatValue]  >= 8.0) {
            //使用期间
            [self.locationManger requestWhenInUseAuthorization];
        }
        [self.locationManger startUpdatingLocation];
    } else {
        
        //[self displayMessage:@"定位功能不可用,请打开定位功能"];
    }
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"error");
    [[DMCAlertCenter defaultCenter] postAlertWithMessage:@"定位失败，请重新定位"];
//    [SVProgressHUD showWithStatus:@"定位失败，请重新定位"];
}
// 6.0 以上调用这个函数
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    isFrist++;
    CLLocation *newLocation = locations[0];
    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
    longitude = @(oldCoordinate.longitude).stringValue;
    latitude = @(oldCoordinate.latitude).stringValue;
    [self.locationManger stopUpdatingLocation];
    if (isFrist ==1) {
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        [geocoder reverseGeocodeLocation:newLocation
                       completionHandler:^(NSArray *placemarks, NSError *error){
                           
                           for (CLPlacemark *place in placemarks) {

                               address = place.locality;
                               
                           }
                       }];
    }

    [[NSUserDefaults standardUserDefaults] setObject:longitude forKey:@"longitude"];
    [[NSUserDefaults standardUserDefaults] setObject:latitude forKey:@"latitude"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
// 6.0 调用此函数
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    
    [self.locationManger stopUpdatingLocation];
    isFrist++;
    if (isFrist ==1) {
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        [geocoder reverseGeocodeLocation:newLocation
                       completionHandler:^(NSArray *placemarks, NSError *error){
                           
                           for (CLPlacemark *place in placemarks) {
                               
//                               NSLog(@"%@",place.addressDictionary);
                               address = place.locality;
                           }
            }];
    }
}
#pragma mark *******************   登录   ************************
- (void)autoLogin {
    
    if (([HQHttpManager userAccount].length&&[HQHttpManager userPassword].length)||([HQHttpManager getUserThirdNO].length&&[HQHttpManager getThirdType].length)) {
        
        if([[defaults objectForKey:@"isFirstComeIn"] intValue] == 1){
            [self setUpRongYun];

            if ([[defaults objectForKey:@"infoStatus"] isEqualToString:@"ok"]) {
                
                
                MZCTabBarController *TabVC =   [[MZCTabBarController alloc] init];
                
                self.window.rootViewController  = TabVC;
            
     
            }
            else if ([[defaults objectForKey:@"infoStatus"] isEqualToString:@"baseinfo"]){
                

                RegisterInfoViewController *infoVC = [[RegisterInfoViewController alloc] init];
                self.window.rootViewController  = infoVC;
                [self.window makeKeyAndVisible];
                
            }else if ([[defaults objectForKey:@"infoStatus"] isEqualToString:@"photo"]){
                

                RegisterPhotoViewController *photoVC = [[RegisterPhotoViewController alloc] init];
                                photoVC.sexNum = [HQHttpManager getUserSex];
                self.window.rootViewController  = photoVC;
            
            }
            [self.window makeKeyAndVisible];

        }else{
            NSString* identifierNumber = [[UIDevice currentDevice].identifierForVendor UUIDString] ;
            NSLog(@"手机序列号: %@",identifierNumber);
            [HQHttpManager userLoginWithAccout:[HQHttpManager userAccount] password:[HQHttpManager userPassword] thirdNO:[HQHttpManager getUserThirdNO] thirdType:[HQHttpManager getThirdType] mode:@"mobile" nickName:nil deviceNo:identifierNumber successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
                [SVProgressHUD dismiss];
                if (isSuccess) {
                    [self setUpRongYun];
                    GifloginViewController *gifVc = [[GifloginViewController alloc] init];
                    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:gifVc];
                    self.window.rootViewController = nav;
                    [self.window makeKeyAndVisible];

                    }
            }];
        }
    }
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
//杀死进程
- (void)applicationWillTerminate:(UIApplication *)application {
    

    [[RCIM sharedRCIM] logout];
    [[ILiveLoginManager getInstance] iLiveLogout:^{
        NSLog(@"腾讯云退出等路");
    } failed:^(NSString *module, int errId, NSString *errMsg) {
        
    }];
    
    //通知服务器  退出房间
    
    [CheekVodeRequest getCheekVodeSigType:@"0" success:^(id sucess) {
        if([sucess[@"code"] isEqualToString:@"ok"]){
            
        }
    } failure:^(NSError *error) {
        
    }];
    //发送C2C消息
    ILVLiveCustomMessage *overLimitMsg = [[ILVLiveCustomMessage alloc] init];
    overLimitMsg.type = ILVLIVE_IMTYPE_C2C;
    overLimitMsg.cmd = (ILVLiveIMCmd)AVIMCMD_Cancel_Back;
    overLimitMsg.recvId = [defaults objectForKey:@"EventhewheatUid"];
    
    
    [[TILLiveManager getInstance] sendOnlineCustomMessage:overLimitMsg succ:^{
        
    } failed:^(NSString *module, int errId, NSString *errMsg) {
        
    }];
    
    
    
    [[TILLiveManager getInstance] unLinkRoom:^{
        
        
    } failed:^(NSString *module, int errId, NSString *errMsg) {
        
    }];
    
    //退出房间
    [[TILLiveManager getInstance] quitRoom:^{
        
        
        
    } failed:^(NSString *module, int errId, NSString *errMsg) {
        
        NSLog(@"exit room fail.module=%@,errid=%d,errmsg=%@",module,errId,errMsg);
        
        
        
    }];
    
    
}
#pragma mark -  个人信息配置
-(void)setPersionalUSD{
    //隐私
    if([defaults objectForKey:@"allowToRecommendMeAddressBookFriends"]==nil){
        [defaults  setObject:@"allowToRecommendMeAddressBookFriendsYES" forKey:@"allowToRecommendMeAddressBookFriends"];
        [defaults synchronize];
    }
    if([defaults objectForKey:@"allowToFindMeByPhoneNum"]==nil){
        [defaults  setObject:@"allowToFindMeByPhoneNumYES" forKey:@"allowToFindMeByPhoneNum"];
        [defaults synchronize];
    }
    if([defaults objectForKey:@"allowToAppearAndShowDistance"]==nil){
        [defaults  setObject:@"allowToAppearAndShowDistanceA"forKey:@"allowToAppearAndShowDistance"];
        [defaults synchronize];
    }
    
    //设置->隐私与通知
    if([defaults objectForKey:@"allowToMessageShake"]==nil){
        [defaults  setObject:@"allowToMessageShakeYES"forKey:@"allowToMessageShake"];
        [defaults synchronize];
    }
    if([defaults objectForKey:@"allowToacceptAllKindsInvitations"]==nil){
        [defaults  setObject:@"allowToacceptAllKindsInvitationsYES"forKey:@"allowToacceptAllKindsInvitations"];
        [defaults synchronize];
    }
    if([defaults objectForKey:@"allowToShowMessagePreviews"]==nil){
        [defaults  setObject:@"allowToShowMessagePreviewsYES"forKey:@"allowToShowMessagePreviews"];
        [defaults synchronize];
    }
    
    
}
//显示小红点
//- (void)showUnreadMessageHotView {
//        [self.tabbar.tabBar showBadgeOnItemIndex:4];
//    
//}
- (void)MessageRequestCount{
    
    
    [HQHttpManager mfWithCount:[HQHttpManager getUserId] successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        if (isSuccess) {
            

            
            
            NSNumber *friendCount = resultDic[@"count"];
            
            
            _friendMessageCount =[friendCount integerValue];
        }
      
    }];
    
    
    
    
//    [HQHttpManager mfWithUid:[HQHttpManager getUserId] successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
//        if (isSuccess) {
//            
//
//            
//            NSNumber *wooCount = resultDic[@"wooUpdateCount"];
//            _friendMessageCount =[wooCount integerValue];
//
//        }
//     
//    }];
    
    
}

@end
